package com.shu.logsearch.util;

import cn.hutool.core.date.DateUtil;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * 强制类型转换工具类
 * 转换异常则返回默认值
 *
 * @author Tree Cai
 * @date 2019/7/1
 */
public class TypeCastUtil {

    public static final int DEFAULT_INT = 0;
    public static final double DEFAULT_DOUBLE = 0;
    public static final long DEFAULT_LONG = 0;
    public static final float DEFAULT_FLOAT = 0;
    public static final String DEFAULT_STRING = "";

    public static String toString(Object object, String defaultStr) {
        return (object == null) ? defaultStr : object.toString();
    }

    public static String toString(Object object) {
        return toString(object, DEFAULT_STRING);
    }

    public static Integer toInt(Object object, Integer defaultInt) {
        try {
            return (object == null) ? defaultInt : Integer.parseInt(toString(object));
        } catch (Exception e) {
            return defaultInt;
        }
    }

    public static Integer toInt(Object object) {
        return toInt(object, DEFAULT_INT);
    }

    public static Long toLong(Object object, Long defaultLong) {
        try {
            return (object == null) ? defaultLong : Long.parseLong(toString(object));
        } catch (Exception e) {
            return defaultLong;
        }
    }

    public static Long toLong(Object object) {
        return toLong(object, DEFAULT_LONG);
    }

    public static Float toFloat(Object object, Float defaultFloat) {
        try {
            return (object == null) ? defaultFloat : Float.parseFloat(toString(object));
        } catch (Exception e) {
            return defaultFloat;
        }
    }

    public static Float toFloat(Object object) {
        return toFloat(object, DEFAULT_FLOAT);
    }

    public static Double toDouble(Object object, Double defaultDouble) {
        try {
            return (object == null) ? defaultDouble : Double.parseDouble(toString(object));
        } catch (Exception e) {
            return defaultDouble;
        }
    }

    public static Double toDouble(Object object) {
        return toDouble(object, DEFAULT_DOUBLE);
    }

    public static Date toDate(Object object, Date defaultDate) {
        try {
            String dateStr = toString(object);
            if (StringUtils.isEmpty(dateStr))
                return defaultDate;
            return DateUtil.parse(dateStr) ;
        } catch (Exception e) {
            return defaultDate;
        }
    }

    public static Date toDate(Object object) {
        return toDate(object,null);
    }


}
